package mobi.greenplate.theweb.resource;

import java.net.URI;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import mobi.greenplate.theweb.converter.UserConverter;
import mobi.greenplate.theweb.converter.UserListConverter;
import mobi.greenplate.theweb.domain.User;
import mobi.greenplate.theweb.repository.UserRepository;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;


@Path("/user")
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class UserResource {

    @Inject
    private UserRepository userRepository;
    @Context
    private UriInfo uriInfo;

    @GET
    @Produces({"application/xml", "application/json"})
    public UserListConverter getUsers(@QueryParam("first") @DefaultValue("0") int first,
            @QueryParam("max") @DefaultValue("10") int max) {
        final List<User> userList = userRepository.findAll(first, max);
        final UserListConverter userListConverter = new UserListConverter(userList);
        return userListConverter;
    }

    @GET
    @Produces({"application/xml", "application/json"})
    @Path("{id}")
    public UserConverter getUserById(@PathParam("id") Long id) {
        final User user = userRepository.findById(id);
        final UserConverter userConverter = new UserConverter(user);
        return userConverter;
    }

    @POST
    @Consumes({"application/xml", "application/json"})
    public Response createUser(UserConverter userConverter) {
        final User forSave = userConverter.getEntity();
        forSave.setId(null); //makes sure it is allways new..
        final User user = userRepository.save(forSave);
        final URI uri = uriInfo.getAbsolutePathBuilder().
                path(user.getId().toString()).
                build();
        return Response.created(uri).build();
    }

    @PUT
    @Consumes({"application/xml", "application/json"})
    @Path("{id}")
    public UserConverter updateOrCreateUser(@PathParam("id") Long id, UserConverter userConverter) {
       //if the resource doesn't exist.. it would be created...with PUT.. could be added additional check ... 
        final User forSave = userConverter.getEntity();
        forSave.setId(id); //makes sure it is exactly the one that has to be updated
        final User user = userRepository.save(forSave);
        return new UserConverter(user);
    }

    @DELETE
    @Path("{id}")
    public void deleteUser(@PathParam("id") Long id) {
       userRepository.delete(id);
    }
}

